<template>
  <div>
    <van-nav-bar class="top" title="登录" />
    <van-form @submit="onSubmit">
      <van-field
        v-model="mobile"
        name="mobile"
        label="手机号"
        required
        placeholder="请输入手机号"
        :rules="[
          { required: true, message: '请输入手机号' },
          {
            pattern: /^1(3[0-9]|5[0-3,5-9]|7[1-3,5-8]|8[0-9])\d{8}$/,
            message: '请输入正确手机号'
          }
        ]"
      />
      <van-field
        v-model="code"
        name="code"
        label="验证码"
        required
        placeholder="请输入验证码"
        :rules="[
          { required: true, message: '请填写验证码' },
          { pattern: /\d{6}/, message: '请正确填写验证码' }
        ]"
      />
      <div style="margin: 16px;">
        <van-button
          round
          block
          type="info"
          native-type="submit"
          :loading="isLoading"
          :disabled="isDisabled"
          loading-text="登录中"
          >提交</van-button
        >
      </div>
    </van-form>
  </div>
</template>

<script>
import { userLogin } from '../../api/login'
import { saveToken, removeToken, getToken } from '../../utils/token'
export default {
  name: 'login',
  data () {
    return {
      mobile: '',
      code: '',
      isLoading: false,
      isDisabled: false
    }
  },
  methods: {
    onSubmit (values) {
      this.isLoading = true
      this.isDisabled = true
      userLogin(values)
        .then(data => {
          this.$toast.success('登录成功！')
          this.isLoading = false
          this.isDisabled = false
          saveToken(data.data.data)
          // 根据url中的地址 决定跳转的路径
          if (this.$route.query.back) {
            // 原路返回
            this.$router.push({ path: this.$route.query.back })
          } else {
            // back没有值
            this.$router.push({ path: '/home' })
          }
        })
        .catch(errdata => {
          this.$toast.fail('验证码有误')
          this.isLoading = false
          this.isDisabled = false
        })
    }
  },
  created () {
    console.log(getToken())
    removeToken()
  }
}
</script>

<style lang="less">
.van-nav-bar.top {
  background: #1989fa;
  .van-nav-bar__title {
    color: #fff;
  }
}
</style>
